import { reverse, sortBy } from 'lodash-es'
import type {
  InventoryReportDetail,
  FacilityActivityTableListItem,
  EmissionSourceActivityTableListItem,
  ActivityGasEmissionFactorTableListItem,
  ActivityGasRatioTableListItem,
  GasRatioTableListItem,
  CategoryGasEmissionTableListItem,
  ActivityGasInfoTableListItem,
  FacilityActivityVo,
  GasTotalEmission,
  GasInfoVo,
  CategoryEmissionRank,
  GasEmissionRank,
  ActivityEmissionRank,
} from './type'

export function countConsecutiveItems(arr: (string | number)[]) {
  if (arr.length === 0)
    return []

  const counts = []
  let current = arr[0]
  let count = 1

  // 遍历数组，从第二个元素开始
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] === current) {
      count++
    }
    else {
      counts.push(count) // 记录当前项的计数
      current = arr[i]
      count = 1
    }
  }

  // 添加最后一个组的计数
  counts.push(count)

  return counts
}

/**
 * 获取需要合并行的行索引数组
 * 比如：['a', 'a', 'a', 'b', 'b', 'c', 'c', 'c']
 * 首页将相同项归纳起来，并记录长度，即[3, 2, 3]
 * 然后计算它们对应的行索引[3, 5, 8]
 * 最后往前补零，再删除最后一项得到[0, 3, 5]
 */
export function getArrRowIndex(arr: (string | number)[]) {
  if (arr.length === 0)
    return []
  const result = [0] // 初始化结果数组，第一个元素总是 0
  let current = arr[0]
  let count = 1

  // 遍历数组，从第二个元素开始
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] === current) {
      count++
    }
    else {
      result.push(result[result.length - 1] + count) // 更新结果数组
      current = arr[i]
      count = 1
    }
  }

  // 由于最后一个组的结束索引不需要，我们直接返回结果数组
  return result
}

/** 转设施活动及排放源列表对象 */
export function convertFacilityActivityTableList(source: InventoryReportDetail): FacilityActivityTableListItem[] {
  const dataList = source.dataList ?? []
  const result: FacilityActivityTableListItem[] = []
  for (const item of dataList) {
    for (const child of item.categoryList) {
      for (const activity of child.facilityActivityList) {
        result.push({
          categoryName: item.xh,
          subCategoryName: child.name,
          activityName: activity.name,
          activityEmissionSource: activity.emissionSource,
        })
      }
    }
  }
  return result
}

/** 转排放源活动数据列表对象 */
export function convertEmissionSourceActivityTableList(source: InventoryReportDetail): EmissionSourceActivityTableListItem[] {
  const dataList = source.dataList ?? []
  const result: EmissionSourceActivityTableListItem[] = []
  for (const item of dataList) {
    for (const child of item.categoryList) {
      for (const { gasList, ...rest } of child.facilityActivityList) {
        result.push({
          ...rest,
        })
      }
    }
  }
  return result
}

/** 转活动气体排放因子列表对象 */
export function convertActivityGasEmissionFactorTableList(source: InventoryReportDetail): ActivityGasEmissionFactorTableListItem[] {
  const dataList = source.dataList ?? []
  const result: ActivityGasEmissionFactorTableListItem[] = []
  const getFactorFromGas = (gas: string, activity: FacilityActivityVo) => {
    const target = activity.gasList.find(v => v.gas.toLowerCase() === gas.toLowerCase())
    return target ? target.emissionFactor * (target.discountValue || 1) : '\\'
  }
  for (const item of dataList) {
    for (const child of item.categoryList) {
      for (const activity of child.facilityActivityList) {
        result.push({
          activityName: activity.name,
          activityEmissionSource: activity.emissionSource,
          activityUnit: activity.unit,
          CO2: getFactorFromGas('co2', activity),
          CH4: getFactorFromGas('ch4', activity),
          N2O: getFactorFromGas('n2o', activity),
          HFCs: getFactorFromGas('hfcs', activity),
          PFCs: getFactorFromGas('pfcs', activity),
          SF6: getFactorFromGas('sf6', activity),
          NF3: getFactorFromGas('nf3', activity),
        })
      }
    }
  }
  return result
}

/** 转温室气体排放量及占比列表对象 */
export function convertGasRatioTableList(source: InventoryReportDetail): GasRatioTableListItem[] {
  const dataList = source.dataList ?? []
  const result: GasRatioTableListItem[] = []
  for (const item of dataList) {
    for (const child of item.categoryList) {
      result.push({
        range: item.range,
        categoryName: item.xh,
        subCategoryName: child.name,
        emission: child.data,
        emissionRatio: `${child.ratio ?? '-'}%`,
      })
    }
  }
  return result
}

/** 转小类活动温室气体排放量及占比列表对象 */
export function convertActivityGasRatioTableList(source: InventoryReportDetail): ActivityGasRatioTableListItem[] {
  const dataList = source.dataList ?? []
  const result: ActivityGasRatioTableListItem[] = []
  for (const item of dataList) {
    for (const child of item.categoryList) {
      for (const activity of child.facilityActivityList) {
        result.push({
          // 避免不同大类下的小类重名
          subCategoryName: `#ID${item.id}#${child.name}`,
          activityName: activity.name,
          emissionNum: activity.data,
          emissionRatio: `${activity.ratio}%`,
        })
      }
    }
  }
  return result
}

/** 转气体排放总量对象 */
export function convertGasTotalEmissionObject(dataList: CategoryGasEmissionTableListItem[]): GasTotalEmission {
  const acculate = (gas: string, list: typeof dataList) => {
    return Number.parseFloat(list.reduce((acc, cur) => {
      acc += Number(cur[gas])
      return acc
    }, 0).toFixed(4))
  }
  return {
    CO2: acculate('CO2', dataList),
    CH4: acculate('CH4', dataList),
    N2O: acculate('N2O', dataList),
    PFCs: acculate('PFCs', dataList),
    HFCs: acculate('HFCs', dataList),
    SF6: acculate('SF6', dataList),
    NF3: acculate('NF3', dataList),
    total: acculate('total', dataList),
  }
}

/** 转类别气体排放量列表对象 */
export function convertCategoryGasEmissionTableList(source: InventoryReportDetail): CategoryGasEmissionTableListItem[] {
  const dataList = source.dataList ?? []
  const result: CategoryGasEmissionTableListItem[] = []
  const sum = (gas: string, list: GasInfoVo[]) => {
    return Number.parseFloat(list.filter(v => v.gas.toLowerCase() === gas.toLowerCase())
      .reduce((acc, cur) => {
        // 温室气体转CO2当量值
        acc += Number.parseFloat(`${cur.dataToCO2}`)
        return acc
      }, 0).toFixed(4))
  }
  for (const item of dataList) {
    let gasOfCategory: GasInfoVo[] = []
    for (const child of item.categoryList) {
      for (const activity of child.facilityActivityList) {
        gasOfCategory = gasOfCategory.concat(activity.gasList)
      }
    }
    const s1 = sum('co2', gasOfCategory)
    const s2 = sum('ch4', gasOfCategory)
    const s3 = sum('n2o', gasOfCategory)
    const s4 = sum('hfcs', gasOfCategory)
    const s5 = sum('pfcs', gasOfCategory)
    const s6 = sum('sf6', gasOfCategory)
    const s7 = sum('nf3', gasOfCategory)

    const s = Math.round((s1 + s2 + s3 + s4 + s5 + s6 + s7 + Number.EPSILON) * 1e6) / 1e6

    result.push({
      categoryName: item.xh,
      CO2: s1,
      CH4: s2,
      N2O: s3,
      HFCs: s4,
      PFCs: s5,
      SF6: s6,
      NF3: s7,
      total: s,
    })
  }
  return result
}

/** 转附录活动气体排放因子说明列表对象 */
export function convertActivityGasInfoTableList(source: InventoryReportDetail): ActivityGasInfoTableListItem[] {
  const dataList = source.dataList ?? []
  const result: ActivityGasInfoTableListItem[] = []
  for (const item of dataList) {
    for (const child of item.categoryList) {
      for (const activity of child.facilityActivityList) {
        for (const gas of activity.gasList) {
          result.push({
            // 避免活动同名
            activityName: `#ID${activity.id}#${activity.name}`,
            activityEmissionSource: `#ID${activity.id}#${activity.emissionSource}`,
            ...gas,
            activitySourceType: activity.sourceType,
            ActivityGasExplain: activity.gasExplain,
          })
        }
      }
    }
  }
  return result
}

/** 转大类的排放量排行 */
export function convertCategoryEmissionRank(source: InventoryReportDetail, n: number): CategoryEmissionRank[] {
  const dataList = source.dataList ?? []
  const data: CategoryEmissionRank[] = dataList.map(v => ({
    xh: v.xh,
    name: v.name,
    data: v.data,
    ratio: `${v.ratio}%`,
  }))
  return reverse(sortBy(data, 'data')).slice(0, n)
}

/** 转小类的排放量排行 */
export function convertSubCategoryEmissionRank(source: InventoryReportDetail, n: number): CategoryEmissionRank[] {
  const dataList = source.dataList ?? []
  const data: CategoryEmissionRank[] = []
  for (const item of dataList) {
    for (const child of item.categoryList) {
      data.push({
        xh: child.xh,
        name: child.name,
        data: child.data,
        ratio: `${child.ratio}%`,
      })
    }
  }
  return reverse(sortBy(data, 'data')).slice(0, n)
}

/** 转气体排放量当量排行 */
export function convertGasEmissionRank(data: any[], n: number): GasEmissionRank[] {
  const list: GasEmissionRank[] = []
  const values = data[0] ?? {}
  const ratios = data[1] ?? {}
  const keys = Object.keys(values)
  for (let i = 0; i < keys.length - 1; i++) {
    const key = keys[i]
    if (!['total', 'categoryName'].includes(key)) {
      list.push({
        gas: key,
        data: values[key],
        ratio: ratios[key],
      })
    }
  }
  return reverse(sortBy(list, 'ratio')).slice(0, n)
}

/** 转活动温室气体排放量排行 */
export function convertActivityEmissionRank(data: ActivityGasRatioTableListItem[], n: number): ActivityEmissionRank[] {
  const result: ActivityEmissionRank[] = []
  for (const item of data) {
    result.push({
      subCategoryName: (item.subCategoryName ?? '').replace(/^#ID\d+#/, ''),
      activityName: item.activityName,
      data: item.emissionNum as number,
      ratio: item.emissionRatio as string,
    })
  }
  return reverse(sortBy(result, 'data')).slice(0, n)
}
